<?php

$date = (isset($_GET['d'])) ? strtotime($_GET['d']) : time();

$year = date("Y", $date);
$month =  date("m", $date);
$monthName = date("F", $date);
$monthDays = date("t", $date);
$today = date("j", time());


$firstDay = date("N", mktime(0, 0, 0, $month, 1, $year));
$lastDay = date("N", mktime(0, 0, 0, $month, $monthDays, $year));

$aAct = (isset($_GET['aAct'])) ? $_GET['aAct'] : '';

switch ($aAct)
{
    case 'addEvent':
        if (addEvent($_POST['date'], $_POST['hasTrained'], $_POST['hasEatenHealthy'], $_POST['comment']))
        {
            $arr = array('success' => true);
            echo json_encode($arr);
            exit();
        }
        else
        {
            $arr = array('success' => false);
            echo json_encode($arr);
            exit();
        }
        $arr = array('success' => false);
        echo json_encode($arr);
        exit();
}
?>
<html>
<head>
    <style>
        * {margin: 0; padding: 0;}

        header
        {
            width: 100%;
            height: 30px;
            background-color: #272727;
        }

        nav
        {
            padding-top: 4px;
            width: 800px;
            margin: 0 auto;
        }

        nav a
        {
            padding-right: 15px;
            display: inline-block;
            color: #FFFFFF;
        }

        form
        {
            display: block;
            position: relative;
            width: 100%;
            background-color: #FFFFFF;
        }

        #content
        {
            width: 800px;
            margin: 0 auto;
            z-index: 1;
        }

        #dayBox
        {
            width: 400px;
            display: none;
            padding: 5px;
            position: absolute;
            top: 20%;
            left: 50%;
            margin-left: -200px;
            background-color: #FFFFFF;
            border: 2px solid gray;
            z-index: 9999;
            box-shadow: 1px 1px 10px rgba(0,0,0,.2);

            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
        }

        #mask
        {
            width: 100%;
            height: 100%;
            display: none;
            position: fixed;
            left: 0;
            top: 0;
            background-color: #FFFFFF;
            opacity: 0.7;
            z-index: 900;
        }

        .week
        {
            display: block;
            margin: 0 auto;
        }

        .day, .today, .lMonthDay, .nMonthDay
        {
            display: inline-block;
            width: 100px;
            height: 100px;
            border: 1px solid gray;
            padding: 5px;
        }

        .lMonthDay, .nMonthDay
        {
            color: gray;
            background-color: #efefef;
        }

        .today
        {
            background-color: #e1f5ff;
        }

        .today:hover
        {
           background-color: #d1e8ff;
            cursor: pointer;
        }

        .day:hover
        {
            background-color: #fcffc2;
            cursor: pointer;
        }

        .hasTrained, .hasEatenHealthy
        {
            float: right;
            font-weight: bold;
        }

        .good
        {
            background-color: #beeeab;
        }
    </style>

    <!-- jQuery Javascript -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
    <script>
        var eventDate;
        $(document).ready(function(){

            $("li").click(function(){
                eventDate = this.id;
                var hT = ($("#"+this.id).find(".hasTrained").length != 0)       ? 'checked' : false;
                var hEH = ($("#"+this.id).find(".hasEatenHealthy").length != 0)  ? true : false;
                $("#cht").attr('checked', hT);
                $("#cheh").attr('checked', hEH);
                $("#dayBox").find("p").html(this.id);
                $("#dayBox").fadeIn(500);
                addMask();
            });

            $(".X").click(function(){
                eventDate = '';
                $("#dayBox").fadeOut(500);
                removeMask();
            });


            $("#eventForm").submit(function(){
                var urlen = '?aAct=addEvent';
                var d = eventDate;
                var hT = (this.elements[0].checked) ? true : false;
                var hEH = (this.elements[1].checked) ? true : false;
                var data = {"date" : d, "hasTrained" : hT, "hasEatenHealthy" : hEH, "comment" : ''};

                $.post(urlen, data, function(response){
                    var obj = $.parseJSON(response);
                    if (obj.success)
                    {
                        updateDay(eventDate, hT, hEH);
                    }
                    else
                    {
                        alert('False');
                    }
                    $("#dayBox").fadeOut();
                    removeMask();
                });
                return false;
            });

            function addMask()
            {
                $("body").append('<div id="mask"></div>');
                $("#mask").fadeIn(300);
            }

            function removeMask()
            {
                $("#mask").fadeOut(300).remove();
            }

            function updateDay(id, hT, hEH)
            {
                if (!hT)
                {
                    $("#"+id).find(".hasTrained").remove();
                }
                else
                {
                    if ($("#"+id).find(".hasTrained").length == 0)
                    {
                        $("#"+id).append('<span class="hasTrained">T</span>');
                    }
                }
                if (!hEH)
                {
                    $("#"+id).find(".hasEatenHealthy").remove();
                }
                else
                {
                    if ($("#"+id).find(".hastEatenHealthy").length == 0)
                    {
                        $("#"+id).append('<span class="hasEatenHealthy">H</span>');
                    }
                }

                if (hT && hEH)
                {
                    $("#"+id).addClass('good');
                }
                else
                {
                    $("#"+id).removeClass('good');
                }
            }

        });
    </script>
</head>
<body>
<header>
    <nav>
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
    </nav>
</header>
<section id="content">
    <h2><?php echo $monthName . ' ' .$year; ?></h2>
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Ragnar
 * Date: 06.08.12
 * Time: 01:15
 * To change this template use File | Settings | File Templates.
 */



//echo $month. '-'.$monthDays.'-'.$today.'-'.$firstDay;

    $events = getMonthEvents($date);

if ($firstDay != 0)
{
    $lastMonth = $month-1;
    $lMonthDays = date("t", mktime(0, 0, 0, $lastMonth, 1, $year));
    $first = $lMonthDays - $firstDay + 2;
    echo '<div class="week">';
    for ($i = $first; $i <= $lMonthDays; $i++)
    {
        echo '<li class="lMonthday">'.$i.'</li>';
    }
}



for ($i = 1; $i <= $monthDays; $i++)
{
    $dayOfWeek          = date("N", mktime(0, 0, 0, $month, $i, $year));
    $class              =  ($i == $today && $month == date("m", time())) ? 'today' : 'day';
    $hasTrained         = '';
    $hasEatenHealthy    = '';
    $good = '';

    if (array_key_exists($i, $events))
    {
        $hasTrained         = ($events[$i]['hasTrained'])       ? '<span class="hasTrained">T</span>'       : '';
        $hasEatenHealthy    = ($events[$i]['hasEatenHealthy'])  ? '<span class="hasEatenHealthy">H</span>'  : '';
        $good               = ($events[$i]['hasTrained'] && $events[$i]['hasEatenHealthy']) ? ' good' : '';
    }

    $tmpDate = $year . '-' . $month . '-' . $i;

    if ($dayOfWeek == 7)
    {
        echo '<li id="'.$tmpDate.'" class="'.$class.$good.'">'.$i.$hasTrained.$hasEatenHealthy.'</li></div><div class="week">';
    }
    elseif ($i == $monthDays && $lastDay == 7)
    {
        echo '<li id="'.$tmpDate.'" class="'.$class.$good.'">'.$i.$hasTrained.$hasEatenHealthy.'</li></div>';
    }
    elseif ($i == $monthDays && $lastDay != 7)
    {
        echo '<li id="'.$tmpDate.'" class="'.$class.$good.'">'.$i.$hasTrained.$hasEatenHealthy.'</li>';
    }
    else
    {
        echo '<li id="'.$tmpDate.'" class="'.$class.$good.'">'.$i.$hasTrained.$hasEatenHealthy.'</li>';
    }
}

if ($lastDay != 7)
{
    $nextMonth = $month+1;
    $nMonthDays = date("t", mktime(0, 0, 0, $nextMonth, 1, $year));
    for ($i = 1; $i <= 7-$lastDay; $i++)
    {
        if ($i == (7-$lastDay))
        {
            echo '<li class="nMonthDay">'.$i.'</li></div>';
        }
        else
        {
            echo '<li class="nMonthDay">'.$i.'</li>';
        }
    }
}

function printMonth()
{

}

function getDay()
{

}
function isFirstDayOfWeek($day)
{
    return ($day == 1) ? true : false;
}

function isLastDayOfWeek($day)
{
    return ($day == 7) ? true : false;
}

?>
</section>

<div id="dayBox">
    <a class="X" href="#">X</a>
    <h3>Legg til event</h3>
    <hr />
    <p></p>
    <form id="eventForm" action="" method="POST">
            <input id="cht" type="checkbox" value="true" /> Har trent
            <input id="cheh" type="checkbox" value="true" /> Har spist sunt
            <input type="submit" value="Lagre" />
    </form>
</div>
</body>
</html>

<?php


    function getMonthEvents($date)
    {
        mysql_connect('localhost', 'root', '');
        mysql_select_db('journal');

        $monthDays = date('t', $date);
        $year = date('Y', $date);
        $month = date('m', $date);

        $start = $year . '-' . $month . '-01';
        $end   = $year . '-' . $month . '-' . $monthDays;

        $sql = sprintf("SELECT `date`, `hasTrained`, `hasEatenHealthy`, `comment` FROM `events` WHERE `date` BETWEEN '%s' AND '%s'", $start, $end);
        $query = mysql_query($sql);
        $retVal = array();
        while ($row = mysql_fetch_assoc($query))
        {
            $dayOfMonth = date('j', strtotime($row['date']));
            $retVal[$dayOfMonth] = $row;
        }
        return $retVal;
    }

    function addEvent($date, $hasTrained = false, $hasEatenHealthy = false, $comment = '')
    {
        if ($date == '')
        {
            return false;
        }
        list($year, $month, $day) = explode("-", $date);
        if (!checkdate($month, $day, $year))
        {
            return false;
        }
        $link = mysql_connect('localhost', 'root', '');
        mysql_select_db('journal');

        $sql = sprintf("SELECT `id` FROM `events` WHERE `date` = '%s';", $date);
        $query = mysql_query($sql);
        $id = 0;
        if (mysql_num_rows($query) == 1)
        {
            $row = mysql_fetch_assoc($query);
            $id = $row['id'];
        }

        if ($id != 0)
        {
            // Update
            $sql = sprintf("UPDATE `events` SET `hasTrained` = %s, `hasEatenHealthy` = %s, `comment` = '%s' WHERE `id` = %s LIMIT 1;", $hasTrained, $hasEatenHealthy, $comment, $id);
            $qu = mysql_query($sql);
        }
        else
        {
            // Insert
            $sql = sprintf("INSERT INTO `events` VALUES(0, '%s', %s, %s, '%s');", $date, $hasTrained, $hasEatenHealthy, $comment);
            $qi = mysql_query($sql);
        }
        return (mysql_affected_rows($link) == 1);
    }

?>